<template>
  <div class="calendar-container">

    <!-- 日历头部：月份导航和统计信息 -->
    <div class="calendar-header">
      <button class="month-nav" @click="prevMonth">
        <i class="icon-arrow">←</i>
      </button>
      <h4 class="current-month">{{ currentYear }}年{{ currentMonth }}月</h4>
      <button class="month-nav" @click="nextMonth">
        <i class="icon-arrow">→</i>
      </button>
      <div class="stats-info">
        <span class="stat-item">全勤: {{ stats.fullAttendance }}天</span>
        <span class="stat-item">迟到: {{ stats.late }}天</span>
        <span class="stat-item">缺勤: {{ stats.absent }}天</span>
        <span class="stat-item">早退: {{ stats.leaveEarly }}天</span>
      </div>
    </div>

    <!-- 星期标题 -->
    <div class="weekdays">
      <div class="weekday">一</div>
      <div class="weekday">二</div>
      <div class="weekday">三</div>
      <div class="weekday">四</div>
      <div class="weekday">五</div>
      <div class="weekday weekend">六</div>
      <div class="weekday weekend">日</div>
    </div>

    <!-- 日历主体 -->
    <div class="calendar-grid">
      <!-- 上个月的日期占位 -->
      <div class="calendar-day prev-month" v-for="day in prevMonthDays" :key="'prev-' + day">
        <span class="day-number">{{ day }}</span>
      </div>

      <!-- 当月日期 -->
      <div
          class="calendar-day current-month"
          v-for="day in currentMonthDays"
          :key="day"
          :class="{
          'today': day === today,
          'weekend': isWeekend(day),
          'late': attendanceRecords[day] === '迟到',
          'absent': attendanceRecords[day] === '缺勤',
          'leave-early': attendanceRecords[day] === '早退',
          'normal': attendanceRecords[day] === '正常'
        }"
      >
        <span class="day-number">{{ day }}</span>
        <span class="status-tag" v-if="attendanceRecords[day]">
          {{ attendanceRecords[day] }}
        </span>
      </div>

      <!-- 下个月的日期占位 -->
      <div class="calendar-day next-month" v-for="day in nextMonthDays" :key="'next-' + day">
        <span class="day-number">{{ day }}</span>
      </div>
    </div>

    <!-- 状态说明 -->
    <div class="status-legend">
      <div class="legend-item">
        <span class="legend-dot normal"></span>
        <span class="legend-text">正常</span>
      </div>
      <div class="legend-item">
        <span class="legend-dot late"></span>
        <span class="legend-text">迟到</span>
      </div>
      <div class="legend-item">
        <span class="legend-dot absent"></span>
        <span class="legend-text">缺勤</span>
      </div>
      <div class="legend-item">
        <span class="legend-dot leave-early"></span>
        <span class="legend-text">早退</span>
      </div>
      <div class="legend-item">
        <span class="legend-dot today"></span>
        <span class="legend-text">今天</span>
      </div>
    </div>

    <div class="make-up-tip">
      <span>忘记打卡？</span>
      <a href="#" class="make-up-link">马上补卡</a>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AttendanceCalendar',
  data() {
    const today = new Date();
    return {
      // 当前显示的年月
      currentYear: today.getFullYear(),
      currentMonth: today.getMonth() + 1, // 月份从1开始
      today: today.getDate(),

      // 默认打卡记录数据（实际项目中从后端获取）
      attendanceRecords: {
        1: '',
        2: '',
        3: '',
        5: '',
        6: '',
        7: '',
        8: '',
        9: '',
        12: '',
        13: '',
        14: '',
        15: '', // 今天
        16: '',
        19: '',
        20: '',
        26: '',
        27: '',
        30: ''
      },

      // 统计数据（实际项目中从后端获取）
      stats: {
        fullAttendance: 18,
        late: 3,
        absent: 2,
        leaveEarly: 1
      },

      params: {},



    };
  },
  computed: {
    // 获取当月天数
    currentMonthDays() {
      return new Date(this.currentYear, this.currentMonth, 0).getDate();
    },

    // 获取当月第一天是星期几（1-7，对应周一到周日）
    firstDayOfMonth() {
      const day = new Date(this.currentYear, this.currentMonth - 1, 1).getDay();
      return day === 0 ? 7 : day; // 转换为周一为1，周日为7
    },

    // 上个月需要显示的天数
    prevMonthDays() {
      const prevMonth = this.currentMonth - 1 || 12;
      const prevYear = prevMonth === 12 ? this.currentYear - 1 : this.currentYear;
      const prevMonthTotalDays = new Date(prevYear, prevMonth, 0).getDate();

      return Array.from({ length: this.firstDayOfMonth - 1 }, (_, i) => {
        return prevMonthTotalDays - (this.firstDayOfMonth - 2 - i);
      });
    },

    // 下个月需要显示的天数
    nextMonthDays() {
      const totalDays = this.prevMonthDays.length + this.currentMonthDays;
      const nextDaysCount = 42 - totalDays; // 6行×7列=42个格子
      return Array.from({ length: nextDaysCount }, (_, i) => i + 1);
    }
  },

  created() {
    this.fetchAttendanceRecords();
  },

  methods: {
    // 切换到上个月
    prevMonth() {
      if (this.currentMonth === 1) {
        this.currentMonth = 12;
        this.currentYear--;
      } else {
        this.currentMonth--;
      }
      this.fetchAttendanceRecords();
    },

    // 切换到下个月
    nextMonth() {
      if (this.currentMonth === 12) {
        this.currentMonth = 1;
        this.currentYear++;
      } else {
        this.currentMonth++;
      }
      this.fetchAttendanceRecords();
    },

    // 判断某天是否为周末
    isWeekend(day) {
      const weekDay = new Date(this.currentYear, this.currentMonth - 1, day).getDay();
      return weekDay === 0 || weekDay === 6; // 0是周日，6是周六
    },

// 发送请求获取考勤记录数据--捕获错误
    fetchAttendanceRecords() {
      this.params = {
        year: this.currentYear,
        month: this.currentMonth
      }
      console.log("请求参数",this.params)
      // 若需要外部调用时能捕获错误，可返回 Promise
      return this.$api.attendance.getAttendanceRecords(this.params).then(res => {
        this.attendanceRecords = res.data;
        // 根据数据总结统计数据
        this.stats = {
          fullAttendance: Object.values(this.attendanceRecords).filter(status => status === '正常').length,
          late: Object.values(this.attendanceRecords).filter(status => status === '迟到').length,
          absent: Object.values(this.attendanceRecords).filter(status => status === '缺勤').length,
          leaveEarly: Object.values(this.attendanceRecords).filter(status => status === '早退').length
        }
      }).catch(err => {
        console.error('获取考勤记录错误详情：', err);
        this.$message.error('获取考勤记录失败，请稍后重试'); // 假设使用 Element UI 等组件的提示
        throw err; // 抛出错误，允许外部调用时用 .catch 捕获
      });
    }

  }

};
</script>

<style scoped>
.calendar-container {
  max-width: 600px;
  min-width: 300px;
  margin: 5vh auto;
  padding: 3vw;
  background-color: #fff;
  border-radius: 1vw;
  box-shadow: 0 0 2vw rgba(0, 0, 0, 0.1);
  font-family: 'Microsoft YaHei', sans-serif;
  font-size: 1rem;
}

.page-title {
  text-align: center;
  margin-bottom: 1.5em;
  font-size: 1.2rem;
  font-weight: bold;
  color: #333;
}

.tab-group {
  display: flex;
  margin-bottom: 1.5em;
  border-bottom: 0.05rem solid #e5e6eb;
}

.tab-button {
  flex: 1;
  padding: 0.8em 0;
  border: none;
  background-color: transparent;
  cursor: pointer;
  font-size: 1rem;
  color: #666;
  transition: all 0.3s ease;
}

.tab-button.active {
  color: #2b8def;
  border-bottom: 0.15rem solid #2b8def;
}

.calendar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1.5em;
  padding: 0 0.5em;
}

.month-nav {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: #666;
  padding: 0.3em;
}

.current-month {
  margin: 0;
  font-size: 1.1rem;
  color: #333;
}

.stats-info {
  display: flex;
  gap: 1em;
  font-size: 0.85rem;
}

.stat-item {
  color: #666;
}

.stat-item:nth-child(2) {
  color: #dc3545;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  margin-bottom: 0.5em;
}

.weekday {
  text-align: center;
  padding: 0.8em 0;
  font-weight: bold;
  font-size: 0.9rem;
  color: #666;
}

.weekday.weekend {
  color: #dc3545;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 0.3em;
}

.calendar-day {
  aspect-ratio: 1; /* 保持正方形 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0.3em;
  position: relative;
  border-radius: 0.3em;
}

.day-number {
  font-size: 0.9rem;
}

/* 上个月和下个月的日期样式 */
.prev-month, .next-month {
  opacity: 0.3;
}

.prev-month .day-number,
.next-month .day-number {
  color: #999;
}

/* 周末样式 */
.weekend {
  background-color: #f9fafc;
}

/* 今天样式 */
.today {
  border: 2px solid #2b8def;
}

/* 打卡状态样式 */
.status-tag {
  position: absolute;
  bottom: 2px;
  font-size: 0.6rem;
  padding: 0.1em 0.3em;
  border-radius: 0.2em;
  color: white;
}

.normal .status-tag {
  background-color: #28a745;
}

.late .status-tag {
  background-color: #dc3545;
}

.absent .status-tag {
  background-color: #ffc107;
  color: #333;
}

.leave-early .status-tag {
  background-color: #007bff;
}

/* 状态说明图例 */
.status-legend {
  display: flex;
  justify-content: center;
  gap: 1.5em;
  margin: 1.5em 0;
  flex-wrap: wrap;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 0.85rem;
}

.legend-dot {
  display: inline-block;
  width: 0.8em;
  height: 0.8em;
  border-radius: 50%;
  margin-right: 0.3em;
}

.legend-dot.normal {
  background-color: #28a745;
}

.legend-dot.late {
  background-color: #dc3545;
}

.legend-dot.absent {
  background-color: #ffc107;
}

.legend-dot.leave-early {
  background-color: #007bff;
}


.legend-dot.today {
  background-color: transparent;
  border: 2px solid #2b8def;
}

.make-up-tip {
  text-align: center;
  font-size: 0.9rem;
  color: #666;
  margin-top: 1em;
}

.make-up-link {
  color: #2b8def;
  text-decoration: none;
  margin-left: 0.3em;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .stats-info {
    display: none; /* 小屏幕隐藏统计信息 */
  }

  .calendar-header {
    justify-content: center;
    gap: 1em;
  }

  .status-legend {
    gap: 1em;
  }

  .legend-item {
    font-size: 0.8rem;
  }
}
</style>